package com.jiayang.hhotel.ui;

import android.Manifest;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.jiayang.hhotel.R;
import com.jiayang.hhotel.adapter.RealNameListAdapter;
import com.jiayang.hhotel.bean.Constant;
import com.jiayang.hhotel.presenter.CertificationPresenter;
import com.jiayang.hhotel.util.CommonUtil;
import com.jiayang.hhotel.util.StringUtil;
import com.jiayang.hhotel.util.ToastUtil;
import com.kernal.passport.sdk.utils.AppManager;
import com.kernal.passport.sdk.utils.CheckPermission;
import com.kernal.passport.sdk.utils.PermissionActivity;
import com.kernal.passport.sdk.utils.SharedPreferencesHelper;
import com.kernal.passportreader.sdk.CameraActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import cn.droidlover.xdroidmvp.mvp.XActivity;
import kernal.idcard.android.ResultMessage;

import static com.kernal.passport.sdk.utils.Devcode.devcode;

/**
 * Created by Administrator on 2017/5/17 0017.
 * 认证页面
 */

public class CertificationActivity extends XActivity<CertificationPresenter> implements View.OnClickListener {

    @BindView(R.id.tv_1)
    View tv1;
    @BindView(R.id.iv_takephoto)
    ImageView ivTakephoto;
    @BindView(R.id.tv_3)
    TextView tv3;
    @BindView(R.id.tv_4)
    View tv4;
    @BindView(R.id.tv_2)
    TextView tv2;

    private ListView lv;
    private TextView deter;//确认上传

    private int time = 0; // 第几次上传身份证

    private String phone = "";//手机号（账号）
    private String password = "";//密码

    private List<String> nameList;//数据标题集合
    private List<String> contentList;//数据内容集合

    private RealNameListAdapter adapter;

    private boolean lastIsCard;//上次上传是否是身份证
    private boolean isAllow;//是否允许此类证件上传

    private String mpPassType = "0";//证件类型：身份证：1；港澳通行证：3；台证：4；护照：直接获取

    private String mpChnName;//中文名字
    private String MpEngFirstName;//英文名字
    private String mpEngSurName;//英文姓氏
    private int mpSex;//性别
    private String mpAddr1;//身份证地址
    private String mpPassprt;//身份证号
    private String mpPassExp;//证件的终止日期
    private String mpBirthDate;//出生日期
    private String mpFolk;//民族
    private String mpNationCode;//国籍
    private String cutPagePath = "";//图片路径

    private int mpClerkAcct;//个人信息帐号（新建时候是-1）


    //权限
    public static final String[] PERMISSION = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,// 写入权限
            Manifest.permission.READ_EXTERNAL_STORAGE, // 读取权限
            Manifest.permission.CAMERA, Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.VIBRATE, Manifest.permission.INTERNET
    };

    @Override
    public void initData(Bundle savedInstanceState) {

        mpClerkAcct = getIntent().getIntExtra(Constant.INTENT_INT_KEY,-1);

        if(mpClerkAcct == -1){
            String str = getIntent().getStringExtra(Constant.INTENT_PROJECT_KEY);
            phone = str.split(",")[0];
            password = str.split(",")[1];
        }

        lv = (ListView) findViewById(R.id.lv_list);
        deter = (TextView) findViewById(R.id.bt_deter);

        deter.setOnClickListener(this);

        isAllow = true;
        // 需要释放掉相机界面
        AppManager.getAppManager().finishAllActivity();
        initTitle(context, true, getString(R.string.shimingrenzheng), R.color.orange_color,null, null);
        initView();
    }

    private void initView() {
        ivTakephoto.setOnClickListener(this);//进入拍照
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_certification;
    }

    @Override
    public CertificationPresenter newP() {
        return new CertificationPresenter();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_takephoto:
                if (time == 2) return;
                /**
                 * 由于在相机界面释放相机等资源会耗费很多时间， 为了优化用户体验，需要在调用相机的那个界面的oncreate()方法中
                 * 调用AppManager.getAppManager().finishAllActivity();
                 * 如果调用和识别的显示界面是同一个界面只需调用一次即可， 如果是不同界面，需要在显示界面的oncreate()方法中
                 * 调用AppManager.getAppManager().finishAllActivity();即可，
                 * 否则会造成相机资源的内存溢出。
                 */
                time++;
                Intent intent = new Intent(CertificationActivity.this, CameraActivity.class);
                if (Build.VERSION.SDK_INT >= 23) {
                    CheckPermission checkPermission = new CheckPermission(this);
                    if (checkPermission.permissionSet(PERMISSION)) {
                        PermissionActivity.startActivityForResult(this, 0,
                                SharedPreferencesHelper.getInt(
                                        getApplicationContext(), "nMainId", 2),
                                devcode, 0, 0, PERMISSION);
                    } else {
                        intent.putExtra("nMainId", SharedPreferencesHelper.getInt(
                                getApplicationContext(), "nMainId", 2));
                        intent.putExtra("devcode", devcode);
                        intent.putExtra("flag", 0);
                        startActivityForResult(intent, 203);
                    }
                } else {
                    intent.putExtra("nMainId", SharedPreferencesHelper.getInt(
                            getApplicationContext(), "nMainId", 2));
                    intent.putExtra("devcode", devcode);
                    intent.putExtra("flag", 0);
                    //CertificationActivity.this.finish();
                    startActivityForResult(intent, 203);
                    //startActivity(intent);
                }
                break;
            case R.id.bt_deter://确认上传
                if(adapter == null){
                    return;
                }
                if(isAllow){
                    CommonUtil.showProgressDialog(this,R.string.loading);
                    initUpDate();
                    getP().loadData(-1L,Constant.LAUGUAGE_FLAG_CHINESE,mpClerkAcct==-1?1:2,mpClerkAcct,mpChnName
                    ,MpEngFirstName,mpEngSurName
                    ,mpSex,mpAddr1,phone,mpPassType, mpPassprt
                    ,mpPassExp
                    ,mpBirthDate,mpFolk
                    ,mpNationCode,cutPagePath
                    ,password,0);
                }else{
                    ToastUtil.Toast(getString(R.string.unsupport_this_kind_card),this);
                }
                break;
        }
    }

    //注册成功
    public void registerSuccess(){
        if(mpClerkAcct == -1){//注册时
            getP().applyJurisdiction();
        }else{//更换个人信息时
            Intent intent = new Intent();
            setResult(RESULT_OK,intent);
            finish();
        }
    }

    //申请使用权限请求成功
    public void applySuccess(){
        CommonUtil.dismissProgressDialog(this);
        Intent intent = new Intent();
        setResult(RESULT_OK,intent);
        finish();
    }

    /**
     * 收集到的数据解析为list
     * @param msg 返回的数据
     */
    private void pressList(boolean isCard , ResultMessage msg){
        if(nameList == null)nameList = new ArrayList<>();
        if(contentList == null)contentList = new ArrayList<>();
        if(isCard && lastIsCard){//判断这次是否扫描的身份证
            for(int i=0;i<msg.GetFieldName.length-1;i++){
                if(nameList.contains(msg.GetFieldName[i])){//若获取的数据与上次的数据一致
                    time = 1;
                    return;
                }
            }
        }else{
            nameList.clear();
            contentList.clear();
        }
        for(int i=0;i<msg.GetRecogResult.length-1;i++){
            if(!StringUtil.isEmpty(msg.GetFieldName[i]) && !msg.GetFieldName[i].equals("保留")){//若标题不为空
                nameList.add(msg.GetFieldName[i]);
                contentList.add(msg.GetRecogResult[i]);
            }
        }
        setAdapter();
        lastIsCard = isCard;
    }

    private void setAdapter(){
        if(adapter == null){
            adapter = new RealNameListAdapter(this,nameList,contentList);
            lv.setAdapter(adapter);
        }else{
            adapter.notifyDataSetChanged();
        }
    }

    /**
     * 初始化上传变量数据( todo 台证和港澳通行证的数据未写)
     */
    private void initUpDate(){
        HashMap<String,String> model = adapter.getContent();
        switch (mpPassType){//证件类型：身份证：1；港澳通行证：3；台证：4；护照：直接获取
            case "1":
                mpChnName = model.get("姓名");
                MpEngFirstName = "";
                mpEngSurName = "";
                mpSex = model.get(getString(R.string.sex)).equals("男")?0:1;
                mpAddr1 = model.get("住址");
                mpPassprt = model.get("公民身份号码");
                mpPassExp = model.get(getString(R.string.effective_date));
                if(mpPassExp.equals("长期")){
                    mpPassType = "";
                }
                mpBirthDate = model.get("出生");
                mpFolk = model.get("民族");
                mpNationCode = "CHN";
                break;
            case "3":
                mpChnName = model.get("姓名");
                MpEngFirstName = "";
                mpEngSurName = "";
                mpSex = model.get(getString(R.string.sex)).equals("男")?0:1;
                mpAddr1 = model.get("住址");
                mpPassprt = model.get("公民身份号码");
                mpPassExp = model.get(getString(R.string.effective_date));
                if(mpPassExp.equals("长期")){
                    mpPassType = "";
                }
                mpBirthDate = model.get("出生");
                mpFolk = model.get("民族");
                mpNationCode = "CHN";
                break;
            case "4":
                mpChnName = model.get("姓名");
                MpEngFirstName = "";
                mpEngSurName = "";
                mpSex = model.get(getString(R.string.sex)).equals("男")?0:1;
                mpAddr1 = model.get("住址");
                mpPassprt = model.get("公民身份号码");
                mpPassExp = model.get(getString(R.string.effective_date));
                if(mpPassExp.equals("长期")){
                    mpPassType = "";
                }
                mpBirthDate = model.get("出生");
                mpFolk = model.get("民族");
                mpNationCode = "CHN";
                break;
            case "13":
                mpChnName = model.get("本国姓名");
                MpEngFirstName = model.get("英文姓名");
                mpEngSurName = model.get("英文姓");
                mpSex = model.get(getString(R.string.sex)).equals("男")?0:1;
                mpAddr1 = "";
                mpPassprt = model.get("护照号码");
                mpPassExp = model.get(getString(R.string.effective_date));
                if(mpPassExp.equals("长期")){
                    mpPassType = "";
                }
                mpBirthDate = model.get("出生日期");
                mpFolk = "";
                mpNationCode = model.get("持证人国籍代码");
                break;
        }
    }

    /**
     * 获取相机界面返回信息
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != 0 && resultCode == 203) {
            cutPagePath = data.getStringExtra("cutPagePath");
            ResultMessage resultMessage = (ResultMessage) data.getSerializableExtra("resultMessage");
            int nid = data.getIntExtra("nMainId", 0);
            ivTakephoto.setImageBitmap(BitmapFactory.decodeFile(cutPagePath));
            switch (nid) {
                case 2://身份证
                    mpPassType="1";
                    pressList(true,resultMessage);
                    break;
                case 9://港澳通行证
                    mpPassType="3";
                    pressList(false,resultMessage);
                    break;
                case 11://大陆居民往来台湾通行证
                    mpPassType="4";
                    pressList(false,resultMessage);
                    break;
                case 13://护照
                    mpPassType="13";
                    pressList(false,resultMessage);
                    break;
                default:
                    isAllow = false;
                    break;
            }
        }
    }
}
